import CryptoJS from 'crypto-js';

export const getEleById = (id: string) => document.getElementById(id);

// 表单序列化
export const serialize = (data: any) => {
    const list: any = [];
    Object.keys(data).forEach((ele) => {
        list.push(`${ele}=${data[ele]}`);
    });
    return list.join('&');
};
export const getObjType = (obj: any) => {
    var toString = Object.prototype.toString;
    var map: any = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object',
    };
    if (obj instanceof Element) {
        return 'element';
    }
    return map[toString.call(obj)];
};
/**
 * 对象深拷贝
 */
export const deepClone = (data: any) => {
    var type = getObjType(data);
    var obj: any;
    if (type === 'array') {
        obj = [];
    } else if (type === 'object') {
        obj = {};
    } else {
        // 不再具有下一层次
        return data;
    }
    if (type === 'array') {
        for (var i = 0, len = data.length; i < len; i++) {
            obj.push(deepClone(data[i]));
        }
    } else if (type === 'object') {
        for (var key in data) {
            obj[key] = deepClone(data[key]);
        }
    }
    return obj;
};

/**
 *加密处理
 */
export const encryption = (params: any) => {
    let { data, type, param, key } = params;
    const result = JSON.parse(JSON.stringify(data));
    if (type === 'Base64') {
        param.forEach((ele: string | number) => {
            result[ele] = btoa(result[ele]);
        });
    } else {
        param.forEach((ele: string | number) => {
            var data = result[ele];
            key = CryptoJS.enc.Latin1.parse(key);
            var iv = key;
            // 加密
            var encrypted = CryptoJS.AES.encrypt(data, key, {
                iv: iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.ZeroPadding,
            });
            result[ele] = encrypted.toString();
        });
    }
    return result;
};

/**
 * 动态插入css
 */
export const loadStyle = (url: string) => {
    const link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = url;
    const head = document.getElementsByTagName('head')[0];
    head.appendChild(link);
};

/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic: string | any[], value: any) => {
    for (let i = 0; i < dic.length; i++) {
        if (dic[i].value === value) {
            return i;
        }
    }
    return -1;
};

/**
 * 生成随机len位数字
 * len: Number 字符串长度
 */
export const randomNum = (len: any, date: any) => {
    let random = (Math.floor(Math.random() * 9) + 1).toString();
    let $chars = '0123456789';
    for (let i = 0; i < len - 1; i++) {
        random += $chars.charAt(Math.floor(Math.random() * 10));
    }
    if (date) random = random + Date.now();
    return random;
};

/**
 * 生成随机字符串
 * len: Number 字符串长度
 * */
export const randomString = function (len: number) {
    len = len || 32;
    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
};

// 转为blob流数据
export function blobData(data: any, type = 'application/json') {
    return new Blob([JSON.stringify(data)], { type: type });
}

//json数据转formdata格式
export function josnToFormData(obj: any = {}, type = 'application/json') {
    let keys = Object.keys(obj);
    let form_data = new FormData();
    keys.forEach((k) => {
        let val = blobData(obj[k], type);
        form_data.append(k, val);
    });
    return form_data;
}

//去除对象空数据
export function objClearNull(obj: any = {}) {
    let keys = Object.keys(obj);
    let res: any = {};
    keys.forEach((k) => {
        let val = obj[k];
        if (val !== '' && val !== null) {
            res[k] = val;
        }
    });
    return res;
}

// 判断是否为引用类型
export function isObject(obj: any): boolean {
    return obj !== null && typeof obj === 'object';
}

// 判断两个数据是否完全一致
export function areEqual(a: any, b: any): boolean {
    if (a === b) return true;
    const isObjectA = isObject(a);
    const isObjectB = isObject(b);
    if (isObjectA && isObjectB) {
        try {
            const isArrayA = Array.isArray(a);
            const isArrayB = Array.isArray(b);
            if (isArrayA && isArrayB) {
                return (
                    a.length === b.length &&
                    a.every((e, i) => {
                        //数组长度相等，每一项都相等
                        return areEqual(e, b[i]); //递归
                    })
                );
            } else if (a instanceof Date && b instanceof Date) {
                return a.getTime() === b.getTime(); //日期时间戳相等
            } else if (!isArrayA && !isArrayB) {
                //两者都不是数组 就剩下正则、方法、普通对象了
                const keysA = Object.keys(a);
                const keysB = Object.keys(b);
                return (
                    keysA.length === keysB.length &&
                    keysA.every((key) => {
                        return areEqual(a[key], b[key]); //key数量一致、并且每个key对应的值相等
                    })
                );
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    } else if (!isObjectA && !isObjectB) {
        //都不是引用类型
        return String(a) === String(b);
    } else {
        return false;
    }
}

// 千分位数据
export const numFormat = function numFormat(num: number | string): string {
    let s: string = String(num);

    let s1: string = s.split('.')[0] || '';
    let s2: string = s.split('.')[1] || '';
    let arr1: string[] = s1.split('');
    let arr2: string[] = s2.split('');

    let len1 = arr1.length;
    let len2 = arr2.length;

    let res1 = [];
    let str1 = s1;
    if (len1 > 3) {
        str1 = '';
        for (let i = 0; i < len1; i++) {
            let ind = i + 1;
            let n = arr1[len1 - ind];
            res1.push(n);
            if (i < len1 && 0 === ind % 3) {
                res1.push(',');
            }
        }
        str1 = res1.reverse().join('');
    }
    let res2 = [];
    let str2 = s2;
    if (len2 > 3) {
        str2 = '';
        for (let i = 0; i < len2; i++) {
            let ind = i + 1;
            let n = arr1[i];
            res2.push(n);
            if (i < len2 && 0 === ind % 3) {
                res2.push(',');
            }
            str2 = res2.join('');
        }
    }
    let res = str1;
    if (str2) {
        res = str1 + '.' + str2;
    }
    return res;
};
